package sisi.suppliers;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.CheckEvent;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.ComboitemRenderer;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Doublebox;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

import sisi.General;
import sisi.payment.Payment;
import sisi.payment.PaymentsController;
import sisi.ports.Port;
import sisi.ports.PortController;
import sisi.products.Product;
import sisi.products.ProductsController;

/**
 * SupplierWindow.java - Controller class for <i>suppliers window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 05/11/2013
 * 
 */
@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class SupplierWindow extends Window implements 
				org.zkoss.zk.ui.ext.AfterCompose {
//window
private Window windowSupplier, windowEditSupplier;
private Textbox tbCerca;
private Listbox boxSupplier;
private List lista_Supplier;
private boolean lNuovo;
private Toolbarbutton buttonSeleziona;
private ListModelList listModelList;
private Integer idSelezionato = 0;

protected Map<String, Object> args;
private Object SupplierItem;
private Supplier modSupplier;
// edit
private Textbox address;
private Intbox supplid;
private Textbox catgdesc;
private Textbox catgid;
private Textbox city;
private Textbox companyname;
private Textbox contactname;
private Textbox contacttitle;
private Textbox country;
private Datebox dtup;
private Textbox email;
private Textbox fax;
private Textbox gsm;
private Textbox homepage;
private Checkbox logicdelete;
private Textbox notes;
private Intbox paymentcode;
private Combobox paymentterms;
private Textbox phone;
private Checkbox physical;
private Intbox portid;
private Textbox postalcode;
private Textbox region;
private Checkbox req;
private Textbox restrictions;
private Doublebox suppliervalut;
private Checkbox trader;
private Listbox boxSupplierPorts, boxSupplierProducts, boxTradersPhysical;

		public void onCreate$windowSupplier(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		String tastoSeleziona = (String) args.get("tastoSeleziona");
		tastoSeleziona = (tastoSeleziona == null || tastoSeleziona.isEmpty() ? "N": tastoSeleziona);
		boolean lTastoSeleziona = tastoSeleziona.equals("S");
		if (!lTastoSeleziona) {
			buttonSeleziona.setVisible(false);
		}
		idSelezionato = (Integer) args.get("idselezionato");

		listModelList = new ListModelList();
		lista_Supplier = new SupplierController().getList(null);
		listModelList.addAll(lista_Supplier);
		boxSupplier.setModel(listModelList);
		boxSupplier.setItemRenderer(new SupplierItemRenderer());

		if (idSelezionato!=null && idSelezionato!=0){
		for (int i = 0; i < lista_Supplier.size(); i++) {
			Supplier record = (Supplier)lista_Supplier.get(i);
			if (record.getSupplid()==idSelezionato.intValue()){
				boxSupplier.setSelectedIndex(i);
				break;
			}
		}
	}

}

	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);

	}

	public void onOK$tbCerca(Event event){
		cerca();
	}

	public void onClick$buttonCerca(Event event) {
		cerca();
	}


	private void cerca(){
		listModelList = new ListModelList();
		lista_Supplier = new SupplierController().getList(tbCerca.getValue());
		listModelList.addAll(lista_Supplier);
		boxSupplier.setModel(listModelList);
		boxSupplier.setItemRenderer(new SupplierItemRenderer());
	}

	public void onDoubleClicked(Event event) {
		if (buttonSeleziona.isVisible()) {
			seleziona();
		} else {
			modifica(false);
		}
	}

	public void onClick$buttonSeleziona(Event event) {

		seleziona();

}

	public void seleziona() {
		if (boxSupplier.getSelectedIndex() >= 0 && buttonSeleziona.isVisible()) {
			Object oSupplier = boxSupplier.getSelectedItem().getAttribute("rigaSupplier");
			String codiceSelezionato = ""+((Supplier) oSupplier).getSupplid();
			Sessions.getCurrent().setAttribute("codiceSupplierSelezionato", codiceSelezionato);
			windowSupplier.detach();
		}
	}

	public void onClick$buttonNuovo(Event event) {
		modifica(true);
	}

	public void onClick$buttonModifica(Event event) {
		modifica(false);
	}

	private void modifica(boolean nuovo){
		try {

			int nIndex = boxSupplier.getSelectedIndex();

			if (!nuovo && nIndex == -1) { // nessuna riga selezionata

				Messagebox.show("Selezionare una riga da modificare", "Information", Messagebox.OK, Messagebox.INFORMATION);

			} else {
				HashMap map = new HashMap();
				if (nuovo){
					map.put("lNuovo", true);
				}
				map.put("boxSupplier", boxSupplier);
				Window finestraEditSupplier = (Window) Executions.createComponents("/editSupplier.zul", null, map);
				finestraEditSupplier.doModal();
			}

		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		}
	}

	public void onClick$buttonCancella(Event event) {

	}

	public class SupplierItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			new Listcell(""+((Supplier) data).getSupplid()).setParent(li);
			new Listcell(""+((Supplier) data).getCompanyname()).setParent(li);
			li.setAttribute("rigaSupplier", data);
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClicked");
		}
	}


// EDIT: NEW/MODIFY
	public void onCreate$windowEditSupplier(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();

		boxSupplier = (Listbox) args.get("boxSupplier");

		if (args.containsKey("lNuovo")) {
			lNuovo = true;
		} else {
			lNuovo = false;
		}

		
		// carico i payment terms
		List<Payment> pt = new PaymentsController().getPaymentList(null);
		
        ListModelList lm = new ListModelList();
        lm.addAll(pt);
        paymentterms.setModel(lm);
        paymentterms.setItemRenderer(new RendererPaymentTerms());
		
		if (!lNuovo) {
			SupplierItem = boxSupplier.getSelectedItem().getAttribute("rigaSupplier");
			modSupplier = new SupplierController().refresh((Supplier) SupplierItem);
			SupplierItem = modSupplier;
			windowEditSupplier.setTitle("Edit Supplier");
			address.setValue(modSupplier.getAddress());
			supplid.setValue(modSupplier.getSupplid());
			catgdesc.setValue(modSupplier.getCatgdesc());
			catgid.setValue(modSupplier.getCatgid());
			city.setValue(modSupplier.getCity());
			companyname.setValue(modSupplier.getCompanyname());
			contactname.setValue(modSupplier.getContactname());
			contacttitle.setValue(modSupplier.getContacttitle());
			country.setValue(modSupplier.getCountry());
			dtup.setValue( (java.util.Date) (modSupplier.getDtup()));
			email.setValue(modSupplier.getEmail());
			fax.setValue(modSupplier.getFax());
			gsm.setValue(modSupplier.getGsm());
			homepage.setValue(modSupplier.getHomepage());
			logicdelete.setChecked(modSupplier.getLogicDelete());
			notes.setValue(modSupplier.getNotes());
			paymentcode.setValue(modSupplier.getPaymentcode());
			paymentterms.setValue(modSupplier.getPaymentterms());
			phone.setValue(modSupplier.getPhone());
			physical.setChecked(modSupplier.getPhysical());
			portid.setValue(modSupplier.getPortid());
			postalcode.setValue(modSupplier.getPostalcode());
			region.setValue(modSupplier.getRegion());
			req.setChecked(modSupplier.getReq());
			restrictions.setValue(modSupplier.getRestrictions());
			suppliervalut.setValue(modSupplier.getSuppliervalut());
			trader.setChecked(modSupplier.getTrader());
			
			// supplier ports
			ListModelList listModelListSPorts = new ListModelList();
			List<Portssupplier> lista_SupplierPorts = new PortssupplierController().getListxIdSupplier(modSupplier.getSupplid());
			listModelListSPorts.addAll(lista_SupplierPorts);
			boxSupplierPorts.setModel(listModelListSPorts);
			boxSupplierPorts.setItemRenderer(new SupplierPortsItemRenderer());			
			
			// supplier products
			ListModelList listModelListSProducts = new ListModelList();
			List<Supplierproduct> lista_SupplierProducts = new SupplierproductController().getListxIdSupplier(modSupplier.getSupplid());
			listModelListSProducts.addAll(lista_SupplierProducts);
			boxSupplierProducts.setModel(listModelListSProducts);
			boxSupplierProducts.setItemRenderer(new SupplierProductsItemRenderer());			
			
			// TradersPhysical
			ListModelList listModelListTradersPhysical = new ListModelList();
			List<Trader> lista_TradersPhysical = new TraderController().getListxIDSupplier(modSupplier.getSupplid());
			listModelListTradersPhysical.addAll(lista_TradersPhysical);
			boxTradersPhysical.setModel(listModelListTradersPhysical);
			boxTradersPhysical.setItemRenderer(new TraderPhysicalItemRenderer());	
			
		} else {
			windowEditSupplier.setTitle("New Supplier");
			
			// supplier ports
			ListModelList listModelListSPorts = new ListModelList();
			boxSupplierPorts.setModel(listModelListSPorts);
			boxSupplierPorts.setItemRenderer(new SupplierPortsItemRenderer());			
			
			// supplier products
			ListModelList listModelListSProducts = new ListModelList();
			boxSupplierProducts.setModel(listModelListSProducts);
			boxSupplierProducts.setItemRenderer(new SupplierProductsItemRenderer());			
			
			// TradersPhysical
			ListModelList listModelListTradersPhysical = new ListModelList();
			boxTradersPhysical.setModel(listModelListTradersPhysical);
			boxTradersPhysical.setItemRenderer(new TraderPhysicalItemRenderer());
			
			modSupplier = new Supplier();
			
		}

	}

	public void onClick$btnAnnulla(Event event){
		windowEditSupplier.detach();
	}
	
	public void onCheck$logicdelete(){
		if (logicdelete.isChecked()){
			//
			if ( Messagebox.show("Do You want really to logically delete this Supplier? Every link ith ports and products will be unabled!", "Deleting",
					Messagebox.YES | Messagebox.NO, Messagebox.QUESTION) != Messagebox.YES) {
				logicdelete.setChecked(false);
				// da fare logic delete ai ports e products relazionati
			}
		} else {
			
		}
	}

	public void onClick$btnConferma(Event event){
		if (lNuovo){
			modSupplier = new Supplier();
		} else {

		}
		String testoMsg = "";

		modSupplier.setAddress(General.toUpperAncheNull(address.getValue()));
		modSupplier.setSupplid(supplid.getValue());
		modSupplier.setCatgdesc(General.toUpperAncheNull(catgdesc.getValue()));
		modSupplier.setCatgid(catgid.getValue());
		modSupplier.setCity(General.toUpperAncheNull(city.getValue()));
		modSupplier.setCompanyname(General.toUpperAncheNull(companyname.getValue()));
		modSupplier.setContactname(General.toUpperAncheNull(contactname.getValue()));
		modSupplier.setContacttitle(General.toUpperAncheNull(contacttitle.getValue()));
		modSupplier.setCountry(General.toUpperAncheNull(country.getValue()));
		modSupplier.setDtup( (dtup.getValue() != null ? (java.sql.Date) sisi.General.date2Sql(dtup.getValue()): null) );
		modSupplier.setEmail(email.getValue());
		modSupplier.setFax(fax.getValue());
		modSupplier.setGsm(gsm.getValue());
		modSupplier.setHomepage(homepage.getValue());
		modSupplier.setLogicDelete(logicdelete.isChecked());
		modSupplier.setNotes(notes.getValue());
		modSupplier.setPaymentcode(paymentcode.getValue());
		modSupplier.setPaymentterms(paymentterms.getValue());
		modSupplier.setPhone(phone.getValue());
		modSupplier.setPhysical(physical.isChecked());
		modSupplier.setPortid(portid.getValue());
		modSupplier.setPostalcode(postalcode.getValue());
		modSupplier.setRegion(General.toUpperAncheNull(region.getValue()));
		modSupplier.setReq(req.isChecked());
		modSupplier.setRestrictions(restrictions.getValue());
		modSupplier.setSuppliervalut( (suppliervalut.getValue()==null?0:suppliervalut.getValue()) );
		modSupplier.setTrader(trader.isChecked());

		if (lNuovo){
			modSupplier = new SupplierController().add(modSupplier);
			testoMsg = "Nuova Supplier: "+ General.trimNull( modSupplier.getCompanyname() );
		} else {
			new SupplierController().update(modSupplier);
			modSupplier = new SupplierController().refresh(modSupplier);
			testoMsg = "Aggiornando Supplier: "+ General.trimNull( modSupplier.getCompanyname() );
		}


		// cancello i ports abbinati al supplier e poi aggiungo quelli della lista
		List<Portssupplier> listaPSDaCancellare = new PortssupplierController().getListxIdSupplier(modSupplier.getSupplid());
		for (Portssupplier portssupplier : listaPSDaCancellare) {
			new PortssupplierController().remove(portssupplier);
		}
		
		ListModelList lmlPS = (ListModelList) boxSupplierPorts.getListModel();
		int i = 1;
		for (Object object : lmlPS) {
			Portssupplier ps = (Portssupplier) object;
			ps.setSuppid(modSupplier.getSupplid());
			ps.setSupname(modSupplier.getCompanyname());
			if (modSupplier.getLogicDelete()!=null && modSupplier.getLogicDelete()){
				ps.setLogicDelete(true);
			}
			ps.setSeq(i++);
			new PortssupplierController().add(ps);
		}

		
		// cancello i products abbinati al supplier e poi aggiungo quelli della lista
		
		List<Supplierproduct> listaSPDaCancellare = new SupplierproductController().getListxIdSupplier(modSupplier.getSupplid());
		for (Supplierproduct supplierproduct : listaSPDaCancellare) {
			new SupplierproductController().remove(supplierproduct);
		}
		
		i = 1;
		ListModelList lmlSP = (ListModelList) boxSupplierProducts.getListModel();
		for (Object object : lmlSP) {
			Supplierproduct sp = (Supplierproduct) object;
			sp.setSupid(modSupplier.getSupplid());
			sp.setSupname(modSupplier.getCompanyname());
			if (modSupplier.getLogicDelete()!=null && modSupplier.getLogicDelete()){
				sp.setLogicDelete(true);
			}
			sp.setSeq(i++);
			new SupplierproductController().add(sp);
		}
		
		
		// cancello i traders physical abbinati al supplier e poi aggiungo quelli della lista
		
		List<Trader> listaTraders = new TraderController().getListxIDSupplier(modSupplier.getSupplid());
		for (Trader trdc : listaTraders) {
			new TraderController().remove(trdc);
		}
		
		i = 1;
		ListModelList lmlTr = (ListModelList) boxTradersPhysical.getListModel();
		for (Object object : lmlTr) {
			Trader tr = (Trader) object;
			if (tr.getPhysicalname()!=null && !tr.getPhysicalname().isEmpty()){
				tr.setTraderid(modSupplier.getSupplid());
				tr.setTradername(modSupplier.getCompanyname());
				tr.setSeq(i++);
				new TraderController().add(tr);
			}
		}
		
		
		General.showNotify( testoMsg, windowEditSupplier);

		windowEditSupplier.detach();

		// aggiorna listbox

		if (lNuovo){
			ListModelList lml = (ListModelList) boxSupplier.getListModel();
			lml.add(modSupplier);
			boxSupplier.setSelectedIndex(lml.indexOf(modSupplier));
		} else {
			ListModelList lml = (ListModelList) boxSupplier.getListModel();
			Object oSupplierItem = boxSupplier.getSelectedItem().getAttribute("rigaSupplier");
			if (lml.indexOf(oSupplierItem) == -1) {
				// non trovato... quindi non lo aggiorno
			} else {
				lml.set(lml.indexOf(oSupplierItem), modSupplier);
			}
		}
	}

	
	public class RendererPaymentTerms implements ComboitemRenderer {
	    public void render(Comboitem item, Object data, int index) throws Exception {
	        item.setLabel(((Payment)data).getTerms());
	        //item.setDescription(""+((Payment)data).getId());
	    }
	}

	// SUPPLIER PORTS
	
	public class SupplierPortsItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			
			Portssupplier ps = (Portssupplier)data;
			
			Integer seq = ps.getSeq();
			seq = (seq==null?0:seq);
			new Listcell(""+seq).setParent(li);
			new Listcell(""+((Portssupplier) data).getPortname()).setParent(li);
			new Listcell(""+((Portssupplier) data).getCountry()).setParent(li);
			
			
			// FUEL
			PortsFuelCheckbox(ps, new Listcell()).setParent(li);			

			// OIL
			PortsOilCheckbox(ps, new Listcell()).setParent(li);
			
			// DELETED
			PortsDeleteCheckbox(ps, new Listcell()).setParent(li);
			
			
			li.setAttribute("rigaSupplierPorts", data);
		}
	}
	
	
	private Listcell PortsFuelCheckbox(final Portssupplier ps, Listcell listcell) {

		Checkbox cbDeleted = new Checkbox();
		cbDeleted.setChecked(ps.getFuel());
		cbDeleted.setParent(listcell);

		cbDeleted.addEventListener("onCheck", new EventListener() {
			public void onEvent(Event event) {
				final CheckEvent evt = (CheckEvent) event;
				Boolean bDeleted = evt.isChecked();
				ps.setFuel(bDeleted);
			} 
		});
		return listcell;
	}
	
	private Listcell PortsOilCheckbox(final Portssupplier ps, Listcell listcell) {

		Checkbox cbDeleted = new Checkbox();
		cbDeleted.setChecked(ps.getOil());
		cbDeleted.setParent(listcell);

		cbDeleted.addEventListener("onCheck", new EventListener() {
			public void onEvent(Event event) {
				final CheckEvent evt = (CheckEvent) event;
				Boolean bDeleted = evt.isChecked();
				ps.setOil(bDeleted);
			} 
		});
		return listcell;
	}
	
	private Listcell PortsDeleteCheckbox(final Portssupplier ps, Listcell listcell) {

		Checkbox cbDeleted = new Checkbox();
		cbDeleted.setChecked(ps.getLogicDelete());
		cbDeleted.setParent(listcell);

		cbDeleted.addEventListener("onCheck", new EventListener() {
			public void onEvent(Event event) {
				final CheckEvent evt = (CheckEvent) event;
				Boolean bDeleted = evt.isChecked();
				ps.setLogicDelete(bDeleted);
			} 
		});
		return listcell;
	}
	
	
	public void onClick$buttonNuovoPort(){
		
		Sessions.getCurrent().setAttribute("codicePortSelezionato", null);
		
		HashMap map = new HashMap();
		map.put("tastoSeleziona", "S");
		Window finestraSelPort = (Window) Executions.createComponents("/port.zul", null, map);
		finestraSelPort.doModal();
			
		String portSelected = (String)Sessions.getCurrent().getAttribute("codicePortSelezionato");
		if (portSelected!=null){
			Port port = new PortController().getPortxId(Integer.valueOf(portSelected));

			// faccio dei controlli e aggiungo la riga
			ListModelList lml = (ListModelList) boxSupplierPorts.getListModel();
			boolean trovato = false;
			for (Object object : lml) {
				
				Portssupplier ps = (Portssupplier) object;
				if (ps.getPortid().equals( port.getId() ) ){
					trovato = true;
					new General().MsgBox("Port "+port.getPortname().trim()+" exist in this list. NOT added!", "Info");
					break;
				}
			}
			
			if( !trovato){
				Portssupplier ps = new Portssupplier();
				ps.setCountry(port.getCountry());
				ps.setFuel(false);
				ps.setPortid(port.getId());
				ps.setLogicDelete(false);
				ps.setPortname(port.getPortname());
				ps.setOil(false);
				ps.setSupname(port.getSn());
				ps.setSuppid(supplid.getValue()); // da re inserire nel salvataggio
				ps.setSupname(companyname.getValue()); // da re inserire nel salvataggio	
				ps.setSeq(boxSupplierPorts.getItemCount()+1);
				lml.add(ps);
				boxSupplierPorts.setSelectedIndex(boxSupplierPorts.getItemCount()-1);
			}
		}
		
	}
	
	public void onClick$buttonCancellaPort(){
		int nIndex = boxSupplierPorts.getSelectedIndex();

		if (nIndex == -1) { // nessuna riga selezionata
			Messagebox.show("Select a row to remove",
					"Information", Messagebox.OK, Messagebox.INFORMATION);
			return;
		} else {
			ListModelList lml = (ListModelList) boxSupplierPorts.getListModel();
			lml.remove(nIndex);
			boxSupplierPorts.setSelectedIndex(nIndex - 1);
		}
	}
	
	
	// SUPPLIER PRODUCTS
	
	public class SupplierProductsItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			
			Supplierproduct sp = (Supplierproduct) data;
			Integer seq = sp.getSeq();
			seq = (seq==null?0:seq);
			new Listcell(""+seq).setParent(li);
			new Listcell(""+((Supplierproduct) data).getProdname()).setParent(li);
			
			ProductsDeleteCheckbox( (Supplierproduct)data, new Listcell()).setParent(li);
			
			li.setAttribute("rigaSupplierProducts", data);
		}
	}

	private Listcell ProductsDeleteCheckbox(final Supplierproduct sp, Listcell listcell) {

		Boolean deleted = sp.getLogicDelete();
		Checkbox cbDeleted = new Checkbox();
		cbDeleted.setChecked(deleted);
		cbDeleted.setParent(listcell);

		cbDeleted.addEventListener("onCheck", new EventListener() {
			public void onEvent(Event event) {
				final CheckEvent evt = (CheckEvent) event;
				Boolean bDeleted = evt.isChecked();
				sp.setLogicDelete(bDeleted);
			} 
		});
		return listcell;
	}
	
	public void onClick$buttonNuovoProduct(){
		
		Sessions.getCurrent().setAttribute("codiceProductSelezionato", null);
		
		HashMap map = new HashMap();
		map.put("tastoSeleziona", "S");
		Window finestraSelProduct = (Window) Executions.createComponents("/products.zul", null, map);
		finestraSelProduct.doModal();
			
		String productSelected = (String)Sessions.getCurrent().getAttribute("codiceProductSelezionato");
		if (productSelected!=null){
			Product product = new ProductsController().getProductxId(Integer.valueOf(productSelected));
			//General.showNotify( "Porto selezionato: "+product.getProductname(), windowEditSupplier);
			
			// faccio dei controlli e aggiungo la riga
			boolean trovato = false;
			ListModelList lml = (ListModelList) boxSupplierProducts.getListModel();
			for (Object object : lml) {
				
				Supplierproduct sp = (Supplierproduct) object;
				if (sp.getProdid().equals( product.getId() ) ){
					trovato = true;
					new General().MsgBox("Product "+product.getProductname().trim()+" exist in this list. NOT added!", "Info");
					break;
				}
			}
			
			if (!trovato){
				Supplierproduct sp = new Supplierproduct();
				sp.setLogicDelete(false);
				sp.setProdid(product.getId());
				sp.setProdname(product.getProductname());
				sp.setSupid(supplid.getValue()); // da re inserire nel salvataggio
				sp.setSupname(companyname.getValue()); // da re inserire nel salvataggio
				sp.setSeq(boxSupplierProducts.getItemCount()+1);
				lml.add(sp);
				boxSupplierProducts.setSelectedIndex(boxSupplierProducts.getItemCount()-1);
			}
			
		}
		
	}
	
	public void onClick$buttonCancellaProduct(){
		int nIndex = boxSupplierProducts.getSelectedIndex();

		if (nIndex == -1) { // nessuna riga selezionata
			Messagebox.show("Select a row to remove",
					"Information", Messagebox.OK, Messagebox.INFORMATION);
			return;
		} else {
			ListModelList lml = (ListModelList) boxSupplierProducts.getListModel();
			lml.remove(nIndex);
			boxSupplierProducts.setSelectedIndex(nIndex - 1);

		}
	}

	
	// TRADER PHYSICAL
	
	public class TraderPhysicalItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			
			Trader trader = (Trader) data;
			
			Integer traderid = trader.getTraderid();
			traderid = (traderid==null?0:traderid);
			String tradername = trader.getTradername();
			Integer physicalid = trader.getPhysicalid();
			physicalid = (physicalid==null?0:physicalid);
			String physicalname = trader.getPhysicalname();
			Integer seq = trader.getSeq();
			seq = (seq==null?0:seq);
			Date date = trader.getDt();
			
			new Listcell(""+traderid).setParent(li);
			new Listcell(""+tradername).setParent(li);
			new Listcell(""+physicalid).setParent(li);
			
			TradersCombobox(trader, new Listcell(), li).setParent(li);
			
			new Listcell(""+seq).setParent(li);
			new Listcell(""+General.formatoFecha(date)).setParent(li);
			
			li.setAttribute("rigaTraderPhysical", data);
		}
	}

	
	private Listcell TradersCombobox(final Trader trader, Listcell listcell, final Listitem li) {

		String tradername = trader.getTradername();
		Combobox cbTrader = new Combobox();
		
		// tutta la lista dei traders/physical
		List<Supplier> listPhysical = new SupplierController().getListPhysical(null);
		final List<Supplier> listPh = listPhysical;
        ListModelList lml = new ListModelList();
        lml.addAll(listPhysical);
        cbTrader.setModel(lml);
        cbTrader.setItemRenderer(new RendererTraders());
        cbTrader.setValue(trader.getPhysicalname());
		cbTrader.setParent(listcell);
		cbTrader.setWidth("300px");
		cbTrader.setAutodrop(true);
		cbTrader.setAutocomplete(true);
			
		cbTrader.addEventListener("onChange", new EventListener() {
			public void onEvent(Event event) {
				Combobox combo = (Combobox) event.getTarget();
				if ( controlloDoppiPhysical(combo, listPh, trader) ){
					Supplier supplier = listPh.get(combo.getSelectedIndex());

					Trader tr = trader;
					tr.setPhysicalid(supplier.getSupplid());	
					tr.setPhysicalname(supplier.getCompanyname()); 
					int indexItem = boxTradersPhysical.getIndexOfItem(li);
					Object oTraderPItem = boxTradersPhysical.getItemAtIndex(indexItem).getAttribute("rigaTraderPhysical");

					ListModelList lml2 = (ListModelList) boxTradersPhysical.getListModel();
					if (lml2.indexOf(oTraderPItem) == -1) {
						// non trovato... quindi non lo aggiorno
					} else {
						lml2.set(lml2.indexOf(oTraderPItem), tr);
					}
				}
			} 
		});
		
		return listcell;
	}
	
	private boolean controlloDoppiPhysical(Combobox combo, List<Supplier> listPh, Trader trader){
		final ListModel<Trader> traderPhysical = boxTradersPhysical.getListModel();
		
		if (combo.getSelectedIndex()<0){
			Messagebox.show("Physical name: "+combo.getValue().trim()+" does not exist in the Physical list", "Information", Messagebox.OK, Messagebox.INFORMATION);
			combo.setSelectedIndex(-1); 
			combo.setValue("");
			return false;
		}
	
		
		Supplier supplier = listPh.get(combo.getSelectedIndex());

		int i = traderPhysical.getSize();
		int totaleItems = 0;
		for (int j = 0; j < i; j++) {
			Trader itemTP = (Trader) traderPhysical.getElementAt(j);
			if (itemTP.getPhysicalid()!=null && itemTP.getPhysicalid().equals(supplier.getSupplid()) && !trader.getSeq().equals( itemTP.getSeq() ) ){
				totaleItems++;
			}
		}
		if (totaleItems>=1){ // esisteva già...
			Messagebox.show("Physical name: "+supplier.getCompanyname().trim()+" exist in this list!",
					"Information", Messagebox.OK, Messagebox.INFORMATION);
			combo.setValue("");
			combo.setSelectedIndex(-1);
			return false;
		}
		
		return true;
	}

	public class RendererTraders implements ComboitemRenderer {
	    public void render(Comboitem item, Object data, int index) throws Exception {
	        item.setLabel(((Supplier)data).getCompanyname());
	        //item.setDescription(""+((Supplier)data).getSupplid());
	    }
	}

	public void onClick$buttonNuovoTrader(){
		// aggiungo riga vuota
		ListModelList lml = (ListModelList) boxTradersPhysical.getListModel();
		Trader trader = new Trader();
		trader.setTraderid(supplid.getValue());
		trader.setTradername(companyname.getValue());
		trader.setSeq(boxTradersPhysical.getItemCount()+1);
		trader.setDt(General.date2Sql( new java.util.Date() ) );
		trader.setPhysicalname("");
		lml.add(trader);
		boxTradersPhysical.setSelectedIndex(boxTradersPhysical.getItemCount()-1);		
	}
	
	public void onClick$buttonCancellaTrader(){
		int nIndex = boxTradersPhysical.getSelectedIndex();

		if (nIndex == -1) { // nessuna riga selezionata
			Messagebox.show("Select a row to remove",
					"Information", Messagebox.OK, Messagebox.INFORMATION);
			return;
		} else {
			ListModelList lml = (ListModelList) boxTradersPhysical.getListModel();
			lml.remove(nIndex);
			boxTradersPhysical.setSelectedIndex(nIndex - 1);
		}
	}
	
}
